//获取应用实例
var WxParse = require('../../wxParse/wxParse.js');
let time = require('../util/date.js');
let wxapi = require('../util/wxapi.js');
const app = getApp();
Page({
  data: {
    goodsList: [],
    commission_vip: 0,
    commission: 0,
    // canvas 
    _width: 0, //手机屏宽
    _heigth: 0, //手机屏高
    swiperHeight: 300, //主图图片高度
    canvasType: false, //canvas是否显示
    loadImagePath: '', //下载的图片
    imageUrl: 'https://cos.myfaka.com/car/service/1.jpg', //主图网络路径
    codeUrl: 'https://www.hnvolvo.com/Public/Upload/gh.jpg', //二维码网络路径
    localImageUrl: '', //绘制的商品图片本地路径
    localCodeUrl: '', //绘制的二维码图片本地路径
  },


  getDeviceInfo: function() {
    let that = this
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          deviceW: res.windowWidth,
          deviceH: res.windowHeight
        })
      }
    })
  },

  onReady() {
    this.getDeviceInfo();
  },
  onLoad: function(options) {
    var that = this;
    that.setData({
      goods_id: options.goodid
    })
    console.log(app.globalData.token)
    if (app.globalData.token == '') {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(function() {
        //要延时执行的代码
        wx.navigateTo({
          url: '/pages/mine/phone-login',
        })
      }, 2000) //延迟时间 这里是1秒
    } else {
      that.getDetail(options.goodid);
    }
  },

  onShow: function() {
    var that = this;
  },

  //预览图片
  previewImage: function(e) {
    var imgUrl = e.currentTarget.dataset.src;
    wx.previewImage({
      urls: [imgUrl], //需要预览的图片http链接列表，注意是数组
      current: '', // 当前显示图片的http链接，默认是第一个
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },


  //获取商品详情
  getDetail: function(goods_id) {
    var that = this;
    var jlV;
    var c1;
    console.log(goods_id)
    wx.request({
      url: app.globalData.api + '/app.php?c=Pdd&a=getGoodsDetail',
      data: {
        token: app.globalData.token,
        goods_id: goods_id,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success(res) {
        console.log(res)
        if (res.data.code == 0) {
          var tempimg;
          jlV = res.data.data.commission_vip / 100
          c1 = res.data.data.goods_details.commission / 100
          for (var i = 0; i < res.data.data.goods_details.goods_gallery_urls.length; i++) {
            tempimg = tempimg + '< img src = ' + res.data.data.goods_details.goods_gallery_urls[i] + ' style = "max-width:100%" />'
          }
          that.setData({
            tempimg: "<html>" + tempimg + "</html>"
          })

          var mingroupPrice = res.data.data.goods_details.min_group_price;
          var coupon_discount = res.data.data.goods_details.coupon_discount;
          var promotion_rate = res.data.data.goods_details.promotion_rate;
          var sum0 = mingroupPrice - coupon_discount;
          var sum1 = sum0 * promotion_rate / 1000;
          var sum3 = sum1 / 100
          // 时间戳转化的日期格式： 2019-02-21 10:04:38
          that.setData({
            urlList: res.data.data.url_list,
            imageUrl: res.data.data.goods_details.goods_gallery_urls[0],
            // codeUrl: res.data.data.goods_details.goods_gallery_urls[1],
            goodsList: res.data.data.goods_details,
            commission_vip: jlV.toFixed(2),
            group_id: app.globalData.group_id,
            ysqdate: time.formatTimeTwo(res.data.data.goods_details.coupon_end_time, 'Y-M-D h:m:s')
          })
          if (app.globalData.group_id == 1) { //会员
            that.setData({
              commission: c1.toFixed(2),
            })
          } else { //淘掌柜
            that.setData({
              commission: jlV.toFixed(2),
            })
          }
          console.log(that.data.ysqdate)
        } else {
          if (res.data.code == 105) {
            wx.removeStorage({
              key: 'token',
              success: function(res) {
                console.log(res)
              },
            })
            app.globalData.token = '';
            wx.reLaunch({
              url: '/pages/mine/phone-login',
            })
          }
          wx.showToast({
            title: '' + res.data.msg,
          })
        }
      }
    })
  },

  //复制文案生成小程序
  copyTxt: function(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  //下载图片
  downloadImg: function(e) { //触发函数
    console.log(e.currentTarget.dataset.url)
    console.log(e.currentTarget.dataset.url.length)
    for (var i = 0; i < e.currentTarget.dataset.url.length; i++) {
      wx.getImageInfo({ //下载图片
        src: e.currentTarget.dataset.url[i], //这里放你要下载图片的数组(多张) 或 字符串(一张)          下面代码不用改动
        success: function(ret) {
          var path = ret.path;
          console.log(ret)
          console.log(path)
          wx.saveImageToPhotosAlbum({
            filePath: path,
            success(result) {
              console.log("成功");
              if (i == e.currentTarget.dataset.url.length) {
                wx.hideLoading();
                wx.showToast({
                  title: '下载图片成功',
                  duration: 2000,
                  mask: true,
                });
              }
            },
            fail(result) {
              console.log("失败,你取消了" + JSON.stringify(result))
              console.log(path);
              wx.openSetting({
                success: (res) => {
                  console.log(res);
                }
              })
            }
          });
        },
        fail(res) {
          console.log(res)
        }
      });
    }

    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  /*按生成图片按钮时*/
  creatQrcodePictures: function(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
    wx.showLoading({
      title: '正在绘制图片',
    })
    /*获取手机宽高*/
    let that = this
    let imgHeigth = this.data.swiperHeight
    let imgUrl = this.data.imageUrl
    let qrcodeUrl = this.data.codeUrl
    wx.getSystemInfo({
      success(res) {
        that.setData({
          _width: res.windowWidth,
          _heigth: res.windowHeight,
          canvasType: true,
        })
        // 获取图片信息生成canvas
        that.getImginfo([imgUrl, qrcodeUrl], 0);
      }
    })
  },
  // 获取图片信息
  getImginfo: function(urlArr, _type) {
    let that = this;
    console.log(urlArr)
    console.log(_type)
    wx.getImageInfo({
      src: urlArr[_type],
      success: function(res) {
        console.log(res)
        //res.path是网络图片的本地地址
        if (_type === 0) { //商品图片
          that.setData({
            localImageUrl: res.path,
          })
          that.getImginfo(urlArr, 1)
        } else {
          that.setData({ //二维码
            localCodeUrl: res.path,
          })
          console.log(res.path)
          console.log("createImg")
          // 创建canvas图片
          that.createNewImg();
        }
      },
      fail: function(res) {
        //失败回调
        console.log('Fail：', _type, res)
      }
    });
  },
  //绘制canvas
  createNewImg: function() {
    let _width = this.data._width,
      _heigth = this.data._heigth; //屏幕宽与高

    let imgHeigth = this.data.swiperHeight, //原图片高度
      scale = (_width - 40) / _width,
      that = this;
    let imgH = imgHeigth * scale; //绘制时图片显示高度  
    let ctx = wx.createCanvasContext('mycanvas');
    // 绘制背景
    ctx.setFillStyle("#fff");
    ctx.fillRect(0, 0, _width, imgH + 160);
    //绘制图片
    console.log(this.data.localImageUrl)
    // ctx.drawImage(this.data.localCodeUrl, 0, 0, 280, 280, 200, 200, 80, 80);
    ctx.drawImage(this.data.localImageUrl, 10, 10, _width, imgH);

    // 绘制标题
    ctx.setFontSize(16);
    ctx.setFillStyle('#000');
    let txtWidth = _width - 10 + 30 - 50; //文字的宽度

    //商品名称
    // 绘制价格单位 '￥'

    if (this.data.goodsList.goods_name.length > 20) {
      ctx.setFontSize(14);
      ctx.setFillStyle('#333');
      ctx.fillText('' + this.data.goodsList.goods_name.substring(0, 20), 10, imgH + 40, txtWidth + 100);
      ctx.setFontSize(14);
      ctx.setFillStyle('#333');
      ctx.fillText('' + this.data.goodsList.goods_name.substring(20, this.data.goodsList.goods_name.length), 10, imgH + 60, txtWidth + 100);
    } else {
      ctx.setFontSize(14);
      ctx.setFillStyle('#333');
      ctx.fillText('' + this.data.goodsList.goods_name.substring(0, 15), 10, imgH + 40, txtWidth + 100);
      ctx.setFontSize(14);
      ctx.setFillStyle('#333');
      ctx.fillText('' + this.data.goodsList.goods_name.substring(15, this.data.goodsList.goods_name.length), 10, imgH + 60, txtWidth + 100);
    }
    // 绘制价格单位 '￥'
    ctx.setFontSize(14);
    ctx.setFillStyle('#d2aa68');
    ctx.fillText('', 10, imgH + 65, txtWidth);
    // 绘制价格
    ctx.setFontSize(14);
    ctx.setFillStyle('red');
    ctx.fillText('劵后价￥' + (this.data.goodsList.min_group_price - this.data.goodsList.coupon_discount) / 100, 10, imgH + 85, txtWidth);
    // 绘制小程序名称
    ctx.setFontSize(14);
    ctx.setFillStyle('red');
    ctx.fillText('下载汇客熊最高省￥' + this.data.commission, 10, imgH + 115, txtWidth);
    // 绘制提示信息
    ctx.setFontSize(14);
    ctx.setFillStyle('#999');
    ctx.fillText('淘宝客小程序• 长按识别', 10, imgH + 145, txtWidth);

    // 绘制二维码
    console.log(this.data.localCodeUrl)

    ctx.drawImage(this.data.localCodeUrl, 0, 0, 350, 350, _width - 120, imgH + 60, 80, 80);
    // 显示绘制
    ctx.draw();
    console.log("开始绘制海报")
    //将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
    setTimeout(function() {
      wx.canvasToTempFilePath({
        canvasId: 'mycanvas',
        success: function(res) {
          var tempFilePath = res.tempFilePath;
          that.setData({
            loadImagePath: tempFilePath,
          });
        },
        fail: function(res) {
          console.log(res);
        }
      });
    }, 500);
    //关闭提示
    wx.hideLoading();
  },
  //点击保存到相册
  saveImg: function() {
    //调用wxapi.js里集成的接口
    console.log(this.data.loadImagePath);
    app.globalData.wxapi.saveImgToLocal(this.data.loadImagePath);
  },
  // 关闭弹窗
  onClickOverlay: function() {
    this.setData({
      canvasType: false
    });
  },

  onShareAppMessage: function(e) {
    if (e.from === 'button') {
      console.log("来自页面内转发按钮");
      console.log(e.target);
      
      return {
        title: '快来汇客熊小程序领取优惠券啦',
        desc: '',
        imageUrl: "/static/images/splash.png",
        path: '/pages/live/splash' // 路径，传递参数到指定页面。
      }
    }
  },
});